package com.jinyi.wwdeng.autodialer.manager

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 计时器
 */
class TimerManager {
    private var job: Job? = null
    private val isRunning = AtomicBoolean(false)

    interface TimerCallback {
        /** 每秒回调一次 */
        fun onTickSecond(second: Int)
        /** 每 interval 秒回调一次 */
        fun onTimerIntervalReached()
    }

    /**
     * @param intervalSec 指定时间间隔秒数
     */
    fun startTimer(intervalSec: Int = 10, callback: TimerCallback) {
        if (isRunning.get()) return

        isRunning.set(true)
        job = CoroutineScope(Dispatchers.Main).launch {
            var elapsed = 0
            while (isRunning.get()) {
                delay(1000)
                elapsed++
                // 每秒回调
                callback.onTickSecond(elapsed)
                // 每 intervalSec 秒回调一次
                if (elapsed % intervalSec == 0) {
                    elapsed = 0
                    callback.onTimerIntervalReached()
                }
            }
        }
    }

    fun stopTimer() {
        isRunning.set(false)
        job?.cancel()
        job = null
    }

    fun isTimerRunning(): Boolean = isRunning.get()
}